<!DOCTYPE html>
<html>
    
<head>
    <meta charset="utf-8">
    
    <title>Kotlin与Java的异同 | ApocalypseBlog</title>
    <canvas id="header_canvas"style="position:absolute;bottom:0"></canvas> 
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    

    

    

    

    
<link rel="stylesheet" href="/dist/build.css?v=1.14.0.css">

    <script src="/javascripts/bubble.js"></script>
    <script>
        window.isPost = true
        window.aomori = {
            
            
        }
        window.aomori_logo_typed_animated = false
        window.aomori_search_algolia = false

    </script>
<script>
    ((window.gitter = {}).chat = {}).options = {
      room: 'ApocalypseBlog/Apocalypse'
    };
  </script>
  <script src="https://sidecar.gitter.im/dist/sidecar.v1.js" async defer></script>
<meta name="generator" content="Hexo 5.3.0"></head>
<!--DaoVoice服务http://blog.daovoice.io/-->

    <script>(function (i, s, o, g, r, a, m) {
        i['DaoVoiceObject'] = r;
        i[r] = i[r] ||
          function () {
            (i[r].q = i[r].q || []).push(arguments);
          };
        i[r].l = 1 * new Date();
        a = s.createElement(o);
        m = s.getElementsByTagName(o)[0];
        a.async = 1;
        a.src = g;
        a.charset = 'utf-8';
        m.parentNode.insertBefore(a, m);
      })(window, document, 'script', ('https:' === document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/b00f5052.js", 'daovoice');
      daovoice('init', {
        app_id: "b00f5052",
      });
      daovoice('update');
    </script>
  
<body>

    <div class="container">
    <header class="header">
        <div class="header-type">
            
            <div class="header-type-inner">
                
                    <a class="header-type-title" href="/">ApocalypseBlog</a>
                
    
                
            </div>
        </div>
        <div class="header-menu">
            <div class="header-menu-inner">
                
            </div>
            <div class="header-menu-social">
                
            </div>
        </div>

        <div class="header-menu-mobile">
            <div class="header-menu-mobile-inner" id="mobile-menu-open">
                <i class="icon icon-menu"></i>
            </div>
        </div>
    </header>

    <div class="header-menu-mobile-menu">
        <div class="header-menu-mobile-menu-bg"></div>
        <div class="header-menu-mobile-menu-wrap">
            <div class="header-menu-mobile-menu-inner">
                <div class="header-menu-mobile-menu-close" id="mobile-menu-close">
                    <i class="icon icon-cross"></i>
                </div>
                <div class="header-menu-mobile-menu-list">
                    
                </div>
            </div>
        </div>
    </div>

</div>

    <div class="container">
        <div class="main">
            <section class="inner">
                <section class="inner-main">
                    <div class="post">
    <article id="post-ckk6o6aum00077kny9722476e" class="article article-type-post" itemscope
    itemprop="blogPost">

    <div class="article-inner">

        
          
        
        
        

        
        <header class="article-header">
            
  
    <h1 class="article-title" itemprop="name">
      Kotlin与Java的异同
    </h1>
  

        </header>
        

        <div class="article-more-info article-more-info-post hairline">

            <div class="article-date">
  <time datetime="2020-06-13T21:47:39.000Z" itemprop="datePublished">2020-06-14</time>
</div>

            

            

            

        </div>

        <div class="article-entry post-inner-html hairline" itemprop="articleBody">
            <h3 id="打印日志"><a href="#打印日志" class="headerlink" title="打印日志"></a>打印日志</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">System.out.print(&quot;hello world&quot;);
System.out.println(&quot;hello world&quot;);</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">print(&quot;hello world&quot;)
println(&quot;hello world&quot;)</code></pre>
<a id="more"></a>

<h3 id="定义变量与常量常"><a href="#定义变量与常量常" class="headerlink" title="定义变量与常量常"></a>定义变量与常量常</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">String name = &quot;hello world&quot;;
final String name = &quot;hello world&quot;;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">var name = &quot;hello world&quot;
val name = &quot;hello world&quot;</code></pre>
<h3 id="null声明"><a href="#null声明" class="headerlink" title="null声明"></a>null声明</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">String otherName;
otherName = null;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">var otherName : String?
otherName = null</code></pre>
<h3 id="空判断"><a href="#空判断" class="headerlink" title="空判断"></a>空判断</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">if (text != null) &#123;
    int length = text.length();
&#125;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">text?.let &#123;
    val length = text.length
&#125;
// or simply
val length = text?.length</code></pre>
<h3 id="字符串拼接"><a href="#字符串拼接" class="headerlink" title="字符串拼接"></a>字符串拼接</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">String firstName = &quot;Android&quot;;
String lastName = &quot;Architect&quot;;
String message = &quot;My name is: &quot; + firstName + &quot; &quot; + lastName;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">val firstName = &quot;Android&quot;
val lastName = &quot;Architect&quot;
val message = &quot;My name is: $firstName $lastName&quot;</code></pre>
<h3 id="换行"><a href="#换行" class="headerlink" title="换行"></a>换行</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">String text = &quot;First Line\n&quot; +
              &quot;Second Line\n&quot; +
              &quot;Third Line&quot;;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">val text = &quot;&quot;&quot;
        |First Line
        |Second Line
        |Third Line
        &quot;&quot;&quot;.trimMargin()</code></pre>
<h3 id="三元表达式"><a href="#三元表达式" class="headerlink" title="三元表达式"></a>三元表达式</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">String text = x &gt; 5 ? &quot;x &gt; 5&quot; : &quot;x &lt;= 5&quot;;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">val text = if (x &gt; 5)
              &quot;x &gt; 5&quot;
           else &quot;x &lt;= 5&quot;</code></pre>
<h3 id="操作符"><a href="#操作符" class="headerlink" title="操作符"></a>操作符</h3><blockquote>
<p>java</p>
</blockquote>
<pre><code class="java">final int andResult  = a &amp; b;
final int orResult   = a | b;
final int xorResult  = a ^ b;
final int rightShift = a &gt;&gt; 2;
final int leftShift  = a &lt;&lt; 2;
final int unsignedRightShift = a &gt;&gt;&gt; 2;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">val andResult  = a and b
val orResult   = a or b
val xorResult  = a xor b
val rightShift = a shr 2
val leftShift  = a shl 2
val unsignedRightShift = a ushr 2</code></pre>
<h3 id="类型判断和转换-声明式"><a href="#类型判断和转换-声明式" class="headerlink" title="类型判断和转换 (声明式)"></a>类型判断和转换 (声明式)</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">Car car = (Car) object;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">var car = object as Car</code></pre>
<h3 id="类型判断和转换-隐式"><a href="#类型判断和转换-隐式" class="headerlink" title="类型判断和转换 (隐式)"></a>类型判断和转换 (隐式)</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">if (object instanceof Car) &#123;
   Car car = (Car) object;
&#125;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">if (object is Car) &#123;
   var car = object // 自动识别
&#125;</code></pre>
<h3 id="多重条件"><a href="#多重条件" class="headerlink" title="多重条件"></a>多重条件</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">if (score &gt;= 0 &amp;&amp; score &lt;= 300) &#123; &#125;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">if (score in 0..300) &#123; &#125;</code></pre>
<h3 id="更灵活的case语句"><a href="#更灵活的case语句" class="headerlink" title="更灵活的case语句"></a>更灵活的case语句</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">int score = // some score;
String grade;
switch (score) &#123;
    case 10:
    case 9:
        grade = &quot;Excellent&quot;;
        break;
    case 8:
    case 7:
    case 6:
        grade = &quot;Good&quot;;
        break;
    case 5:
    case 4:
        grade = &quot;OK&quot;;
        break;
    case 3:
    case 2:
    case 1:
        grade = &quot;Fail&quot;;
        break;
    default:
        grade = &quot;Fail&quot;;
&#125;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">var score = // some score
var grade = when (score) &#123;
    9, 10 -&gt; &quot;Excellent&quot;
    in 6..8 -&gt; &quot;Good&quot;
    4, 5 -&gt; &quot;OK&quot;
    in 1..3 -&gt; &quot;Fail&quot;
    else -&gt; &quot;Fail&quot;
&#125;</code></pre>
<h3 id="for循环"><a href="#for循环" class="headerlink" title="for循环"></a>for循环</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">for (int i = 1; i &lt;= 10 ; i++) &#123; &#125;

for (int i = 1; i &lt; 10 ; i++) &#123; &#125;

for (int i = 10; i &gt;= 0 ; i--) &#123; &#125;

for (int i = 1; i &lt;= 10 ; i+=2) &#123; &#125;

for (int i = 10; i &gt;= 0 ; i-=2) &#123; &#125;

for (String item : collection) &#123; &#125;

for (Map.Entry&lt;String, String&gt; entry: map.entrySet()) &#123; &#125;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">for (i in 1..10) &#123; &#125;

for (i in 1 until 10) &#123; &#125;

for (i in 10 downTo 0) &#123; &#125;

for (i in 1..10 step 2) &#123; &#125;

for (i in 10 downTo 0 step 2) &#123; &#125;

for (item in collection) &#123; &#125;

for ((key, value) in map) &#123; &#125;</code></pre>
<h3 id="更方便的集合操作"><a href="#更方便的集合操作" class="headerlink" title="更方便的集合操作"></a>更方便的集合操作</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">final List&lt;Integer&gt; listOfNumber = Arrays.asList(1, 2, 3, 4);

final Map&lt;Integer, String&gt; keyValue = new HashMap&lt;Integer, String&gt;();
map.put(1, &quot;Android&quot;);
map.put(2, &quot;Ali&quot;);
map.put(3, &quot;Mindorks&quot;);

// Java 9
final List&lt;Integer&gt; listOfNumber = List.of(1, 2, 3, 4);

final Map&lt;Integer, String&gt; keyValue = Map.of(1, &quot;Android&quot;,
                                             2, &quot;Ali&quot;,
                                             3, &quot;Mindorks&quot;);</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">val listOfNumber = listOf(1, 2, 3, 4)
val keyValue = mapOf(1 to &quot;Android&quot;,
                     2 to &quot;Ali&quot;,
                     3 to &quot;Mindorks&quot;)</code></pre>
<h3 id="遍历"><a href="#遍历" class="headerlink" title="遍历"></a>遍历</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">// Java 7 and below
for (Car car : cars) &#123;
  System.out.println(car.speed);
&#125;

// Java 8+
cars.forEach(car -&gt; System.out.println(car.speed));

// Java 7 and below
for (Car car : cars) &#123;
  if (car.speed &gt; 100) &#123;
    System.out.println(car.speed);
  &#125;
&#125;

// Java 8+
cars.stream().filter(car -&gt; car.speed &gt; 100).forEach(car -&gt; System.out.println(car.speed));</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">cars.forEach &#123;
    println(it.speed)
&#125;

cars.filter &#123; it.speed &gt; 100 &#125;
      .forEach &#123; println(it.speed)&#125;</code></pre>
<h3 id="方法定义"><a href="#方法定义" class="headerlink" title="方法定义"></a>方法定义</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">void doSomething() &#123;
   // logic here
&#125;

void doSomething(int... numbers) &#123;
   // logic here
&#125;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">fun doSomething() &#123;
   // logic here
&#125;

fun doSomething(vararg numbers: Int) &#123;
   // logic here
&#125;</code></pre>
<h3 id="带返回值的方法"><a href="#带返回值的方法" class="headerlink" title="带返回值的方法"></a>带返回值的方法</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">int getScore() &#123;
   // logic here
   return score;
&#125;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">fun getScore(): Int &#123;
   // logic here
   return score
&#125;

// as a single-expression function

fun getScore(): Int = score</code></pre>
<h3 id="无结束符号"><a href="#无结束符号" class="headerlink" title="无结束符号"></a>无结束符号</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">int getScore(int value) &#123;
    // logic here
    return 2 * value;
&#125;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">fun getScore(value: Int): Int &#123;
   // logic here
   return 2 * value
&#125;

// as a single-expression function

fun getScore(value: Int): Int = 2 * value</code></pre>
<h3 id="constructor-构造器"><a href="#constructor-构造器" class="headerlink" title="constructor 构造器"></a>constructor 构造器</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">public class Utils &#123;

    private Utils() &#123;
      // This utility class is not publicly instantiable
    &#125;

    public static int getScore(int value) &#123;
        return 2 * value;
    &#125;

&#125;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">class Utils private constructor() &#123;

    companion object &#123;

        fun getScore(value: Int): Int &#123;
            return 2 * value
        &#125;

    &#125;
&#125;

// another way

object Utils &#123;

    fun getScore(value: Int): Int &#123;
        return 2 * value
    &#125;

&#125;</code></pre>
<h3 id="Get-Set-构造器"><a href="#Get-Set-构造器" class="headerlink" title="Get Set 构造器"></a>Get Set 构造器</h3><blockquote>
<p>Java</p>
</blockquote>
<pre><code class="java">public class Developer &#123;

    private String name;
    private int age;

    public Developer(String name, int age) &#123;
        this.name = name;
        this.age = age;
    &#125;

    public String getName() &#123;
        return name;
    &#125;

    public void setName(String name) &#123;
        this.name = name;
    &#125;

    public int getAge() &#123;
        return age;
    &#125;

    public void setAge(int age) &#123;
        this.age = age;
    &#125;
&#125;</code></pre>
<blockquote>
<p>Kotlin</p>
</blockquote>
<pre><code class="kotlin">data class Developer(val name: String, val age: Int)</code></pre>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a target="_blank" rel="noopener" href="https://class.imooc.com/sale/mobilearchitect">慕课网移动端架构师成长体系课</a></li>
</ul>

        </div>

    </div>

    

    

    

    

    

    
<nav class="article-nav">
  
    <a href="/2020/06/16/100%E8%A1%8Cjs%E4%BB%A3%E7%A0%81%E4%B8%8B%E8%BD%BD%E6%8A%96%E9%9F%B3%E6%97%A0%E6%B0%B4%E5%8D%B0%E8%A7%86%E9%A2%91/" id="article-nav-newer" class="article-nav-link-wrap">
      <div class="article-nav-caption">下一篇</div>
      <div class="article-nav-title">
        
          100 行 js 代码下载抖音无水印视频
        
      </div>
    </a>
  
  
    <a href="/2020/06/14/%E7%82%AB%E9%85%B7%EF%BC%81%E4%BB%8E%E6%9C%AA%E8%A7%81%E8%BF%87%E5%A6%82%E6%AD%A4Q%E5%BC%B9%E7%9A%84Switcher/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-caption">上一篇</div>
      <div class="article-nav-title">炫酷！从未见过如此Q弹的Switcher</div>
    </a>
  
</nav>


    <section class="share">
        <div class="share-title">分享</div>
        <a class="share-item" target="_blank"
            href="https://twitter.com/share?text=Kotlin与Java的异同 - ApocalypseBlog&url=http://example.com/2020/06/14/Kotlin%E4%B8%8EJava%E7%9A%84%E5%BC%82%E5%90%8C/">
            <box-icon type='logo' name='twitter'></box-icon>
        </a>
        <a class="share-item" target="_blank"
            href="https://www.facebook.com/sharer.php?title=Kotlin与Java的异同 - ApocalypseBlog&u=http://example.com/2020/06/14/Kotlin%E4%B8%8EJava%E7%9A%84%E5%BC%82%E5%90%8C/">
            <box-icon name='facebook-square' type='logo' ></box-icon>
        </a>
        <!-- <a class="share-item" target="_blank"
            href="https://service.weibo.com/share/share.php?title=Kotlin与Java的异同 - ApocalypseBlog&url=http://example.com/2020/06/14/Kotlin%E4%B8%8EJava%E7%9A%84%E5%BC%82%E5%90%8C/&pic=">
            <div class="n-icon n-icon-weibo"></div>
        </a> -->
    </section>

</article>









</div>
                </section>
            </section>

             
            <aside class="sidebar">
            
                
            </aside>
        </div>
    </div>

    <footer class="footer">
    <div class="footer-wave">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="#3c4859" fill-opacity="1" d="M0,160L60,181.3C120,203,240,245,360,240C480,235,600,181,720,186.7C840,192,960,256,1080,261.3C1200,267,1320,213,1380,186.7L1440,160L1440,320L1380,320C1320,320,1200,320,1080,320C960,320,840,320,720,320C600,320,480,320,360,320C240,320,120,320,60,320L0,320Z"></path></svg>
    </div>

    <div class="footer-wrap">
        <div class="footer-inner"> 
            ApocalypseBlog &copy; 2021<br>
            Powered By Hexo · Theme By <a href="https://github.com/lh1me/hexo-theme-aomori" target="_blank">Aomori</a>
        </div>
    </div>

</footer>




<script src="/dist/build.js?1.14.0.js"></script>


<script src="/dist/custom.js?1.14.0.js"></script>









</body>

</html>